package com.lh.glassmuseum.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fazecast.jSerialComm.SerialPort;
import com.lh.glassmuseum.config.SerialPortConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class SerialPortService {
    private static SerialPort serialPort;
    public static SerialPortConfig config;
    private static final Logger LOGGER = LoggerFactory.getLogger(SerialPortService.class);

    public static boolean initSerialPort(){
        try {
            InputStream inputStream = new FileInputStream("C:\\config\\config.json");
//        InputStream inputStream = SerialPortService.class.getClassLoader().getResourceAsStream("config.json");
//            if (inputStream == null) {
//                LOGGER.error("初始化串口失败:未找到配置文件");
//                TipService.updateDisplay("初始化串口失败:未找到配置文件");
//                return false;
//
//            }
            config = JSON.parseObject(
                    inputStream,
                    StandardCharsets.UTF_8,  // 指定编码（可选）
                    SerialPortConfig.class
            );
        } catch (Exception e) {
            LOGGER.error(String.format("初始化串口失败:读取文件错误:%s",e.getMessage()));
            TipService.updateDisplay(String.format("初始化串口失败:读取文件错误:%s",e.getMessage()));
            return false;
        }
        LOGGER.info("加载到配置文件信息:{}", JSONObject.toJSONString(config));
        // 初始化串口
        serialPort = SerialPort.getCommPort(config.getComPort());
        serialPort.setBaudRate(config.getBaudRate());
        serialPort.setParity(SerialPort.NO_PARITY);
        serialPort.setNumStopBits(SerialPort.ONE_STOP_BIT);
        serialPort.setNumDataBits(8);
        //测试开闸
        if (serialPort.openPort()) {
            serialPort.closePort();
        }else{
            LOGGER.error("打开串口失败");
            //打印打开串口失败
            TipService.updateDisplay("打开串口失败");
            return false;
        }
        return true;
    }
    // 发送指令
    public static boolean sendSerialCommand() {
        if (serialPort.openPort()) {
            LOGGER.info("发送开闸指令:{}", config.getCmd());
            byte[] data = hexStringToByteArray(config.getCmd());
            if(null==data){
                TipService.updateDisplay("发送开闸指令失败");
                return false;
            }
            int result = serialPort.writeBytes(data, data.length);
            serialPort.closePort();
            return result!=-1;
        }else{
            LOGGER.error("打开串口失败");
            //打印打开串口失败
            TipService.updateDisplay("打开串口失败");
            return false;
        }
    }

    private static byte[] hexStringToByteArray(String s) {
        s = s.replaceAll("\\s+", ""); // 移除所有空格
        if (s.length() % 2 != 0) {
            LOGGER.error("十六进制长度必须为偶数");
            return null;
        }
        byte[] data = new byte[s.length() / 2];
        for (int i = 0; i < s.length(); i += 2) {
            int high = Character.digit(s.charAt(i), 16) << 4;
            int low = Character.digit(s.charAt(i + 1), 16);
            data[i / 2] = (byte) (high + low);
        }
        return data;
    }
}
